# -*- coding: utf-8 -*-
"""
Created on Thu Jun 26 14:31:20 2025

@author: Administrator
"""

from docx import Document
import os


def clearkh(num_empty_lines):
    num_empty_lines = 1
    # 找到最后一个表格的位置
    last_table_index = -1
    for i, element in enumerate(doc.element.body):
        if element.tag.endswith('tbl'):
            last_table_index = i

    if last_table_index == -1:
        print("文档中未找到表格")
    else:
        # 获取最后一个表格之前的所有段落
        paragraphs_before_last_table = []
        for i, p in enumerate(doc.paragraphs):
            if i < last_table_index:
                paragraphs_before_last_table.append(p)
            else:
                break

        # 从后往前删除指定数量的空段落
        empty_lines_deleted = 0
        for p in reversed(paragraphs_before_last_table):
            if empty_lines_deleted >= num_empty_lines:
                break

            if not p.text.strip():
                p._element.getparent().remove(p._element)
                p._element._parent = None
                empty_lines_deleted += 1
    return


# 打开文档
input_dir = r"E:\20199\三调制图python代码\2025\李沛丹凤\111"
for filename in os.listdir(input_dir):
    if filename.endswith(".docx") and not filename.startswith("~$"):
        file_path = os.path.join(input_dir, filename)
        # 打开文档
        doc = Document(file_path)
        clearkh(4)
        

doc = Document(r"E:\20199\三调制图python代码\2025\李沛丹凤\111\611022001004100001_何军社.docx")  # 请替换为实际的文档路径
# 要删除的空行数量，5对应只有一页地块,4对应2个地块页,3对应3个地块页
# num_empty_lines = 1



clearkh(3)



    # 保存修改后的文档
    output_path = r"E:/20199/三调制图python代码/2025/李沛丹凤/222/何军社.docx"  # 请替换为实际的文档路径
    doc.save(output_path)
    print(f"已删除最后一个表格前的 {empty_lines_deleted} 个空行")
    print(f"已处理文档并保存至: {output_path}")